package daoImpl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.query.Query;

import bean.House;
import bean.User;
import dao.HouseDao;
import util.HibernateUtils;

public class HouseDaoImpl implements HouseDao {
	HibernateUtils hu = new HibernateUtils();
	public boolean addhouse(House house) {
		Session session=hu.getSession();
		session.beginTransaction();
		String hql="from House where title=:n";
		Query query=session.createQuery(hql);
		query.setParameter("n", house.getTitle());
		List<House> u=query.list();
		if(u.isEmpty()){
			session.save(house);
			session.getTransaction().commit();
			hu.closeSession(session);
			return true;
		}else{
	    hu.closeSession(session);
		return false;
	}
	}
	
	public List<House> showHouse() {
		Session session = hu.getSession();
		String hql = "from House";
		Query query = session.createQuery(hql);
		List<House> u = query.list();
		hu.closeSession(session);
		return u;
	}
	public List<House> show1House(House house){
		Session session=hu.getSession();
		session.beginTransaction();
		String hql = "from House where id=:n";
		Query query=session.createQuery(hql);
		query.setParameter("n", house.getId());
		List<House> u=query.list();
		session.getTransaction().commit();
		hu.closeSession(session);
		return u;
	}
	
	public boolean delHouse(House house ){
		Session session = hu.getSession();
		session.beginTransaction();
		String hql = "from House where id=:n";
		Query query = session.createQuery(hql);
		query.setParameter("n", house.getId());
		List<House> u=query.list();
		if(u.size()!=0){
			session.delete(u.get(0));
		}
		session.getTransaction().commit();
		hu.closeSession(session);
		return true;
	}

public boolean updateHouse(House house){
	Session session = hu.getSession();
	session.beginTransaction();
	String hql = "from House where id=:n";
	Query query = session.createQuery(hql);
	query.setParameter("n", house.getId());
	List<House> u=query.list();
	if(u.size()!=0){
		System.out.println(u.get(0));
		 u.get(0).setTitle(house.getTitle());
	}
	/*House u = (House)session.get(House.class, house.getId());
    u.setTitle(house.getTitle());*/
	session.getTransaction().commit();
	hu.closeSession(session);
	return true;
	
}
}
